package com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.zhinenghuacangku_liaocheng.R;
import com.xiaoxing.zhinenghuacangku_liaocheng.R2;
import com.xiaoxing.zhinenghuacangku_liaocheng.di.component.DaggerLiaoCheng_OutOfTheLibraryComponent;
import com.xiaoxing.zhinenghuacangku_liaocheng.di.module.LiaoCheng_OutOfTheLibraryModule;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.contract.LiaoCheng_OutOfTheLibraryContract;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.model.entity.OutOfTheLibraryList;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.presenter.LiaoCheng_OutOfTheLibraryPresenter;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.adapter.OutOfTheLibraryAdapter;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.entity.OutOfTheLibrary;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.entity.XinyemianhuanchongweiBean;
import com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.utils.SPUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_LIAO_CHENG_OUT_OF_THE_LIBRARY_ACTIVITY)
public class LiaoCheng_OutOfTheLibraryActivity extends BaseActivity
        <LiaoCheng_OutOfTheLibraryPresenter> implements LiaoCheng_OutOfTheLibraryContract.View, OnRefreshListener, OutOfTheLibraryAdapter.ChuKuInterface {


    private static boolean mIsNeedDemo = true;
    private static Disposable mDisposable;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;
    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R2.id.et_shou_ji_hao)
    EditText etShouJiHao;
    @BindView(R2.id.tv_cha_xun)
    TextView tvChaXun;
    String namess = "";
    private OutOfTheLibraryAdapter mAdapter;
    private List<OutOfTheLibrary.DataBean> mDataBeanList = new ArrayList<>();
    private List<OutOfTheLibraryList> groups = new ArrayList<OutOfTheLibraryList>();// 组元素数据列表
    private Map<String, List<OutOfTheLibraryList.OutListBean>> children = new HashMap<String, List<OutOfTheLibraryList.OutListBean>>();// 子元素数据列表
    private Map<Integer, Integer> mGroupsPosition = new HashMap<>();
    private String mid = "";
    private String instoreBufferId;
    private String mOutStorageListId;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLiaoCheng_OutOfTheLibraryComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .liaoCheng_OutOfTheLibraryModule(new LiaoCheng_OutOfTheLibraryModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.zhi_neng_cang_ku_liao_cheng_activity_out_of_the_library; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, "出库");

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        intervalTransfered();

    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(false);
    }
//    @Override
////    protected void onDestroy() {
////        super.onDestroy();
////        mAdapter = null;
////        mDataBeanList = null;
////        groups = null;
////        children = null;
////        mGroupsPosition = null;
////        mMidHashMap = null;
////        mInstoreBufferIdHashMap = null;
////    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(LiaoCheng_OutOfTheLibraryActivity.this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(LiaoCheng_OutOfTheLibraryActivity.this, VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new OutOfTheLibraryAdapter(LiaoCheng_OutOfTheLibraryActivity.this, groups, children, mGroupsPosition));
        //优化嵌套卡顿
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setItemViewCacheSize(600);
        RecyclerView.RecycledViewPool recycledViewPool = new RecyclerView.RecycledViewPool();
        mRecyclerView.setRecycledViewPool(recycledViewPool);
        mAdapter.setChuKuInterface(this);
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void intervalTransfered() {

        Observable.interval(30, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        mDisposable = disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        getSearchData();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void getSearchData() {
        if (etShouJiHao != null)
            if (!TextUtils.isEmpty(getShouJiHao())) {
//                mRecyclerView.setVisibility(View.GONE);
//                mEmptyLayout.setVisibility(View.VISIBLE);
//                mGroupsPosition.clear();
//                children.clear();
//                groups.clear();
//
//                mAdapter.setDataItems(new ArrayList<>());
//                mAdapter.notifyDataSetChanged();
//                if (mPresenter != null)
//                    mPresenter.searchOutStorageListAutoStore(OutOfTheLibraryActivity.this, getShouJiHao(), mSharedPreferencesHelper.getString(BaseConstants.UID));
                searchOutStorageListAutoStore(getShouJiHao(), mSharedPreferencesHelper.getString(BaseConstants.UID));
            }
    }

    @NonNull
    private String getShouJiHao() {
        return etShouJiHao.getText().toString().trim();
    }

    /**
     * 查询待出库列表
     *
     * @param userPhone 手机号
     * @param uid       仓管员登录app的id
     * @return
     */
    private void searchOutStorageListAutoStore(String userPhone, String uid) {

        showLoading();

        String methodName = "SearchOutStorageListAutoStore";
        SoapParams params = new SoapParams();
        params.put("userPhone", userPhone);
        params.put("uid", uid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    List<OutOfTheLibraryList> outOfTheLibraryLists = ArmsUtils.parseString2List(result, OutOfTheLibraryList.class);
                    mGroupsPosition.clear();
                    children.clear();
                    groups.clear();
                    mEmptyLayout.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.VISIBLE);
                    mAdapter.setDataItems(getSampleItems(outOfTheLibraryLists));
                    mAdapter.notifyDataSetChanged();
                    mAdapter.expandAll();
                } else {
                    clearData();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    public List<OutOfTheLibraryAdapter.OrderListItem> getSampleItems(List<OutOfTheLibraryList> outOfTheLibraryLists) {
        List<OutOfTheLibraryAdapter.OrderListItem> items = new ArrayList<>();

        for (int i = 0; i < outOfTheLibraryLists.size(); i++) {

            int groupPosition = items.size();
            mGroupsPosition.put(groupPosition, i);

            OutOfTheLibraryList outOfTheLibraryList = outOfTheLibraryLists.get(i);

            groups.add(outOfTheLibraryList);
            items.add(new OutOfTheLibraryAdapter.OrderListItem(outOfTheLibraryList));

            List<OutOfTheLibraryList.OutListBean> outList = outOfTheLibraryList.getOut_list();

            List<OutOfTheLibraryList.OutListBean> products = new ArrayList<OutOfTheLibraryList.OutListBean>();


            for (int i1 = 0; i1 < outList.size(); i1++) {

                OutOfTheLibraryList.OutListBean outListBean = outList.get(i1);


                products.add(outListBean);

                items.add(new OutOfTheLibraryAdapter.OrderListItem(groupPosition, outListBean, i1, outOfTheLibraryList.getOut_storagelist_batchid()));
            }

            children.put(String.valueOf(groupPosition), products);// 将组元素的一个唯一值，这里取Id，作为子元素List的Key

        }
//        items.add(new OutOfTheLibraryAdapter.OrderListItem("", "", "", ""));

        return items;
    }

    public void clearData() {
        mGroupsPosition.clear();
        children.clear();
        groups.clear();
        mEmptyLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null)
            mDisposable.dispose();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        mRefreshLayout.finishRefresh();
    }

    @Override
    public void searchOutStorageListAutoStoreSuccess(List<OutOfTheLibraryList> outOfTheLibraryLists) {
        mGroupsPosition.clear();
        children.clear();
        groups.clear();
        mEmptyLayout.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.VISIBLE);
        mAdapter.setDataItems(getSampleItems(outOfTheLibraryLists));
        mAdapter.notifyDataSetChanged();
        mAdapter.expandAll();


    }

    @Override
    public void returnMaterialAutoStoreSuccess(String returnMaterialAutoStore) {

    }

    @Override
    public void callAutoMachineGetMaterialSuccess(String callAutoMachineGetMaterial) {

//        if (callAutoMachineGetMaterial.equals("true")) {
        ArmsUtils.makeText(this, "正在出库...");
//        } else {
//            ArmsUtils.makeText(this, "出库失败");
//        }

    }

    @Override
    public void outStoreForAndroidAutoSuccess(String outStoreForAndroidAuto) {
        getSearchData();
    }

    @Override
    public void returnMaterialAllAutoStoreSuccess(String returnMaterialAllAutoStore) {
        getSearchData();
    }

    @Override
    public void UpdateOutStorageListBackStatusSuccess(String updateOutStorageListBackStatus) {


    }

    @Override
    public void UpdateOutStorageListScanBufferStatusSuccess(String updateOutStorageListScanBufferStatus) {
        getSearchData();
    }

    @Override
    public void UpdateOutStorageListScanMaterialStatusSuccess(String updateOutStorageListScanMaterialStatus) {
//        getSearchData();
    }

    @Override
    public void UpdateOutStorageListOutStatusSuccess(String updateOutStorageListOutStatus) {

    }

    @Override
    public void finishErrorTaskSuccess(String finishErrorTask) {
        getSearchData();
    }

    @Override
    public void resetOutStorageListScanStatusSuccess(String finishErrorTask) {

        if (finishErrorTask.equals("true")) {
            ArmsUtils.makeText(getContext(), "重置成功");
        } else if (finishErrorTask.equals("false")) {
            ArmsUtils.makeText(getContext(), "重置失败");
        }
        getSearchData();

    }

    @Override
    public void searchNoData() {
        mGroupsPosition.clear();
        children.clear();
        groups.clear();
        mEmptyLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
        mAdapter.setDataItems(new ArrayList<>());
        mAdapter.notifyDataSetChanged();
    }

    @OnClick(R2.id.tv_cha_xun)
    public void chaXunChuKuDan() {

        if (TextUtils.isEmpty(getShouJiHao())) {
            ArmsUtils.makeText(this, "请输入手机号查询");
            return;
        }
//        if (!ArmsUtils.isMobileNO(getShouJiHao())) {
//            ArmsUtils.makeText(this, "输入的手机号格式错误");
//            return;
//        }
//        mPresenter.searchOutStorageListAutoStore(this, getShouJiHao(), mSharedPreferencesHelper.getString(BaseConstants.UID));
        searchOutStorageListAutoStore(getShouJiHao(), mSharedPreferencesHelper.getString(BaseConstants.UID));
//        mAdapter.shuas();

    }

    @Override
    public void saoMiaoWuLiao(String out_storageList_id) {
        mOutStorageListId = out_storageList_id;
        Intent newIntent = new Intent(this, com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.activity.LiaoCheng_ScanQRCodeActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
        // 开始一个新的 Activity等候返回结果
        startActivityForResult(newIntent, 101);
    }

    @Override
    public void editSheZhiHeDuiXuHao(String out_storageList_id, String heDuiXuHao) {
        mOutStorageListId = out_storageList_id;

//        mid = heDuiXuHao;
        mid = SPUtil.getString(LiaoCheng_OutOfTheLibraryActivity.this, "shuru", "");

        ArmsUtils.makeText(getContext(), "核对序号设置成功");
//        mPresenter.UpdateOutStorageListScanMaterialStatus(getContext(), mOutStorageListId, "1", mid);
        UpdateOutStorageListScanMaterialStatus(mOutStorageListId, "1", mid);
    }

    /**
     * 扫描物料的时候调用，更新后台状态
     *
     * @param out_storageList_id 待出库列表中绑定的out_storageList_id
     * @param mStatus)           状态  1是操作过
     * @return 返回值:agv的taskId
     */
    private void UpdateOutStorageListScanMaterialStatus(String out_storageList_id, String mStatus, String mid) {

        showLoading();

        String methodName = "UpdateOutStorageListScanMaterialStatus";
        SoapParams params = new SoapParams();
        params.put("out_storageList_id", out_storageList_id);
        params.put("mStatus", mStatus);
        params.put("mid", mid);


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void saoHuanChongWei(String out_storageList_id) {
        mOutStorageListId = out_storageList_id;
        Intent newIntent = new Intent(this, com.xiaoxing.zhinenghuacangku_liaocheng.mvp.ui.activity.LiaoCheng_ScanQRCodeActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 102);
        // 开始一个新的 Activity等候返回结果
        startActivityForResult(newIntent, 102);
    }

    @Override
    public void yunHui(String out_storageList_id, String mid) {
//        mPresenter.returnMaterialAutoStore(this, out_storageList_id, mid, mSharedPreferencesHelper.getString(BaseConstants.UID));
        returnMaterialAutoStore(out_storageList_id, mid, mSharedPreferencesHelper.getString(BaseConstants.UID));
    }

    @Override
    public void shunBianNaHuo(String out_storageList_id) {
        OutStoreMaterialDirectFromLiKuBuffer(out_storageList_id);
    }

    /**
     * @param
     * @return
     * @method
     * @description 顺便取货
     * @date: 2020/10/21 0021 10:05
     * @author: 小星
     */
    private void OutStoreMaterialDirectFromLiKuBuffer(String out_storageList_id) {

        showLoading();

        String methodName = "OutStoreMaterialDirectFromLiKuBuffer";
        SoapParams params = new SoapParams();
        params.put("out_storageList_id", out_storageList_id);


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (result.equals("true")) {
                        showMessage("发送成功");
                    } else {
                        showMessage("发送失败");
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @SuppressLint("LongLogTag")
    @Override
    public void wanCheng(String mid, String out_storageList_id, String taskId, String scanMid, String scanInstoreBufferId) {
        if (!TextUtils.isEmpty(scanMid)) {
            this.mid = scanMid;
        }
        if (!TextUtils.isEmpty(scanInstoreBufferId)) {
            this.instoreBufferId = scanInstoreBufferId;
        }
//        if (TextUtils.isEmpty(this.mid)) {
//            ArmsUtils.makeText(this, "请扫描物料二维码");
//            return;
//        }
//        if ( Arrays.asList(SPUtil.getString(LinYi_OutOfTheLibraryActivity.this,"smids","").split(",")).contains(mid)){
//            Toast.makeText(LinYi_OutOfTheLibraryActivity.this,"二维码与当前物料匹配",Toast.LENGTH_LONG).show();
//        }else {
//
//            Toast.makeText(LinYi_OutOfTheLibraryActivity.this,"二维码与当前物料不匹配",Toast.LENGTH_LONG).show();
//            return;
//        }
//        if (!this.mid.equals(mid)) {
//            ArmsUtils.makeText(this, "二维码与当前物料不匹配");
//            return;
//        }
//        if (TextUtils.isEmpty(instoreBufferId)) {
//            ArmsUtils.makeText(this, "请扫描缓冲位二维码");
//            return;
//        }

//        mPresenter.outStoreForAndroidAuto(this, mSharedPreferencesHelper.getString(BaseConstants.UID), this.mid, out_storageList_id, instoreBufferId, taskId);
        outStoreForAndroidAuto(mSharedPreferencesHelper.getString(BaseConstants.UID), this.mid, out_storageList_id, instoreBufferId, taskId);
    }

    /**
     * 出库
     *
     * @param uid                登录用户id
     * @param mid                扫描出库缓冲区物品上的二维码id
     * @param out_storageList_id 扫描出库缓冲区的二维码id
     * @param bufferId           待出库列表中绑定的out_storageList_id
     * @param taskId             待出库列表中绑定的taskID
     * @return 返回值: 1:出库成功 0:出库失败 2:未全部出完 需要运回
     */
    @SuppressLint("LongLogTag")
    private void outStoreForAndroidAuto(String uid, String mid, String out_storageList_id, String bufferId, String taskId) {

        showLoading();

        String methodName = "OutStoreForAndroidAuto";
        SoapParams params = new SoapParams();
        params.put("uid", uid);
        params.put("mid", mid);
        params.put("out_storageList_id", out_storageList_id);
//        params.put("buffername", SPUtil.getString(LiaoCheng_OutOfTheLibraryActivity.this, "shuruhuanchongwei", ""));//bufferId
        if (SPUtil.getString(this, "shuruhuanchongwei", "").contains("0")) {
            params.put("buffername", SPUtil.getString(this, "shuruhuanchongwei", ""));
        } else {
            params.put("buffername", String.format("%02d", Integer.parseInt(SPUtil.getString(this, "shuruhuanchongwei", ""))));
        }

        params.put("taskId", taskId);

        Log.e("pppppppppppppp======1========", mid);
        Log.e("pppppppppppppp=======2=======", out_storageList_id);
        Log.e("pppppppppppppp=======3=======", SPUtil.getString(LiaoCheng_OutOfTheLibraryActivity.this, "shuruhuanchongwei", ""));
        Log.e("pppppppppppppp=======4=======", taskId);
        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                Log.e("dayinjieguo==============", result);
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    getSearchData();

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void quXiaoNaHuo(String mid, String out_storageList_id, String taskId, String scanMid, String scanInstoreBufferId) {
        this.mid = scanMid;
        this.instoreBufferId = scanInstoreBufferId;
//        if (TextUtils.isEmpty(this.mid)) {
//            ArmsUtils.makeText(this, "请扫描物料二维码");
//            return;
//        }
//        if (!this.mid.equals(mid)) {
//            ArmsUtils.makeText(this, "二维码与当前物料不匹配");
//            return;
//        }
//        if (TextUtils.isEmpty(instoreBufferId)) {
//            ArmsUtils.makeText(this, "请扫描缓冲位二维码");
//            return;
//        }

//        mPresenter.returnMaterialAllAutoStore(this, mSharedPreferencesHelper.getString(BaseConstants.UID), this.mid, out_storageList_id, instoreBufferId, taskId);
        returnMaterialAllAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID), this.mid, out_storageList_id, instoreBufferId, taskId);

    }

    /**
     * 取消拿货
     *
     * @param uid                登录用户id
     * @param mid                扫描出库缓冲区物品上的二维码id
     * @param out_storageList_id 扫描出库缓冲区的二维码id
     * @param bufferId           待出库列表中绑定的out_storageList_id
     * @param taskId             待出库列表中绑定的taskID
     * @return 返回值: 1:出库成功 0:出库失败 2:未全部出完 需要运回
     */
    private void returnMaterialAllAutoStore(String uid, String mid, String out_storageList_id, String bufferId, String taskId) {

        showLoading();

        String methodName = "ReturnMaterialAllAutoStore";
        SoapParams params = new SoapParams();
        params.put("uid", uid);
        params.put("mid", mid);
        params.put("out_storageList_id", out_storageList_id);
//        params.put("bufferName", SPUtil.getString(LiaoCheng_OutOfTheLibraryActivity.this, "shuruhuanchongwei", ""));
        if (SPUtil.getString(this, "shuruhuanchongwei", "").contains("0")) {
            params.put("bufferName", SPUtil.getString(this, "shuruhuanchongwei", ""));
        } else {
            params.put("bufferName", String.format("%02d", Integer.parseInt(SPUtil.getString(this, "shuruhuanchongwei", ""))));
        }

        params.put("taskId", taskId);


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    getSearchData();

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void chuKu(String out_storagelist_batchid) {
//        mPresenter.callAutoMachineGetMaterial(this, out_storagelist_batchid, mSharedPreferencesHelper.getString(BaseConstants.UID));
        callAutoMachineGetMaterial(out_storagelist_batchid, mSharedPreferencesHelper.getString(BaseConstants.UID));
    }

    @Override
    public void chuKu1(String out_storageList_id) {

        getChuKuHuanChongWei(out_storageList_id);
    }

    public void getChuKuHuanChongWei(String out_storageList_id) {
        showLoading();
//        String methodNames = "GetBatchFreeInstoreBuffer";
        String methodNames = "GetLiKuEntryBuffer";
        SoapParams params = new SoapParams();
        params.put("out_storagelistId", out_storageList_id);

        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodNames + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    try {

                        List<XinyemianhuanchongweiBean> xinyemianhuanchongweiBeanList = ArmsUtils.parseString2List(result, XinyemianhuanchongweiBean.class);
                        showXuanZeChuKuCangWeiDialog(xinyemianhuanchongweiBeanList, out_storageList_id);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    showMessage("没有出库位可选");
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    public void showXuanZeChuKuCangWeiDialog(List<XinyemianhuanchongweiBean> xinyemianhuanchongweiBeans, String out_storageList_id) {

        ArrayList<String> list = new ArrayList<String>();
//        ArrayList<String> listIds = new ArrayList<String>();
        HashMap<String, String> dataIds = new HashMap<>();

        for (int i = 0; i < xinyemianhuanchongweiBeans.size(); i++) {
            list.add(xinyemianhuanchongweiBeans.get(i).getBuffer_name() + "(" + (xinyemianhuanchongweiBeans.get(i).getBuffer_status().equals("0") ? "空闲" : "有任务") + ")");
//            listIds.add(xinyemianhuanchongweiBeans.get(i).getId());
            dataIds.put(xinyemianhuanchongweiBeans.get(i).getBuffer_name() + "(" + (xinyemianhuanchongweiBeans.get(i).getBuffer_status().equals("0") ? "空闲" : "有任务") + ")", xinyemianhuanchongweiBeans.get(i).getId());
        }

//        final String[] items = new String[]{"选项1", "选项2", "选项3", "选项4", "选项5", "选项6", "选项1", "选项2", "选项3", "选项4", "选项5", "选项6", "选项1", "选项2", "选项3", "选项4", "选项5", "选项6"};
        String[] items = new String[list.size()];
        list.toArray(items);

        QMUIDialog.CheckableDialogBuilder builder = new QMUIDialog.CheckableDialogBuilder(getContext())
                .setCheckedIndex(0)
                .setTitle("选择出库仓位")
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });

        builder.addAction("取消", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
            }
        });
        builder.addAction("提交", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
//                String result = "你选择了 " + items[builder.getCheckedIndex()] + "  out_storageList_id=" + out_storageList_id + "   index=" + builder.getCheckedIndex();
//
//                Toast.makeText(getContext(), result, Toast.LENGTH_SHORT).show();
//                dialog.dismiss();

//                chuKU1(out_storageList_id, items[builder.getCheckedIndex()]);
                dialog.dismiss();
                String selectedIs = dataIds.get(items[builder.getCheckedIndex()]);
                LogUtils.debugEInfo("selectedIs=" + selectedIs);
//                chuKU1(out_storageList_id, listIds.get(builder.getCheckedIndex()));
                chuKU1(out_storageList_id, selectedIs);
            }
        });
        builder.create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }

    private void chuKU1(String out_storageList_id, String outbufferid) {

        showLoading();
        String methodName = "CallAutoMachineGetMaterialDirect";
        SoapParams params = new SoapParams();
        params.put("out_storageList_id", out_storageList_id);
        params.put("outbufferid", outbufferid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    ArmsUtils.makeText(getContext(), "正在出库...");
                    getSearchData();
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void setScanMid(String scanMid) {
//        if (!TextUtils.isEmpty(scanMid))
//            mid = scanMid;
    }

    @Override
    public void setScanInstoreBufferId(String scanInstoreBufferId) {
//        if (!TextUtils.isEmpty(instoreBufferId))
//            instoreBufferId = scanInstoreBufferId;
    }

    @Override
    public void finishErrorTask(String out_storageList_id) {

        if (!TextUtils.isEmpty(out_storageList_id))
//            mPresenter.finishErrorTask(this, out_storageList_id);
            finishErrorTask1(out_storageList_id);
    }

    /**
     * 处理异常
     *
     * @param
     * @return
     */
    private void finishErrorTask1(String out_storagelist_batchid) {
        showLoading();


        String methodName = "FinishErrorTask";
        SoapParams params = new SoapParams();
        params.put("out_storageList_id", out_storagelist_batchid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    getSearchData();

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void resetOutStorageListScanStatus(String out_storageList_id) {
        if (!TextUtils.isEmpty(out_storageList_id)) {

//            HashMap<String, String> map = new HashMap<>();
//            map.put("out_storageList_id", out_storageList_id);
//            mPresenter.resetOutStorageListScanStatus(getContext(), map);
            resetOutStorageListScanStatus1(out_storageList_id);
        }
    }

    /**
     * 出库扫描物料或缓冲位置出错时，重置扫描状态
     * public bool ResetOutStorageListScanStatus(string out_storageList_id)
     *
     * @param
     * @return
     */
    private void resetOutStorageListScanStatus1(String out_storageList_id) {

        showLoading();

        String methodName = "ResetOutStorageListScanStatus";
        SoapParams params = new SoapParams();
        params.put("out_storageList_id", out_storageList_id);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (result.equals("true")) {
                        ArmsUtils.makeText(getContext(), "重置成功");
                    } else if (result.equals("false")) {
                        ArmsUtils.makeText(getContext(), "重置失败");
                    }
                    getSearchData();

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 手动调用机器人
     *
     * @param out_storagelist_batchid 入参:out_storagelist_batchid:上一步返回的out_storagelist_batchid
     * @return 返回值:添加任务是否成功 true:添加任务成功 false:添加任务失败
     */
    private void callAutoMachineGetMaterial(String out_storagelist_batchid, String uid) {

        showLoading();

        String methodName = "CallAutoMachineGetMaterial";
        SoapParams params = new SoapParams();
        params.put("out_storagelist_batchid", out_storagelist_batchid);
        params.put("uid", uid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    ArmsUtils.makeText(getContext(), "正在出库...");

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 运回
     *
     * @param out_storageList_id 待出库列表中绑定的out_storageList_id
     * @param mid                待出库列表中绑定的mid
     * @param uid                登录用户id
     * @return 返回值:agv的taskId
     */
    private void returnMaterialAutoStore(String out_storageList_id, String mid, String uid) {

        showLoading();

        String methodName = "ReturnMaterialAutoStore";
        SoapParams params = new SoapParams();
        params.put("out_storageList_id", out_storageList_id);
        params.put("mid", mid);
        params.put("uid", uid);


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (Integer.parseInt(result) > 0) {
                        showMessage("发送成功");
                    } else {
                        showMessage("发送失败");
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 101) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                mid = extras.getString("scan_result");

//                mPresenter.UpdateOutStorageListScanMaterialStatus(getContext(), mOutStorageListId, "1", mid);
                UpdateOutStorageListScanMaterialStatus(mOutStorageListId, "1", mid);

            }
        } else if (resultCode == 102) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                instoreBufferId = extras.getString("scan_result");
//                mPresenter.UpdateOutStorageListScanBufferStatus(getContext(), mOutStorageListId, "1", instoreBufferId);
                UpdateOutStorageListScanBufferStatus(mOutStorageListId, "1", instoreBufferId);

            }
        }
    }

    private void UpdateOutStorageListScanBufferStatus(String out_storageList_id, String bufferStatus, String bufferId) {

        showLoading();

        String methodName = "UpdateOutStorageListScanBufferStatus";
        SoapParams params = new SoapParams();
        params.put("out_storageList_id", out_storageList_id);
        params.put("bufferStatus", bufferStatus);
        params.put("bufferId", bufferId);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    getSearchData();

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }
}
